export default {
  namespaced: true, //命名空间
  state: {
    cartData: [],
  },
  mutations: {
    SET_CART(state, payload) {
      // state.cartData = payload

      //1.先检查cartData有没有传入这条数据、
      let target = state.cartData.find((item) => item.id === payload.id);
      //-没有 将数据添加到cartData，第一次加入进来数量为1，需要手动添加count这个字段
      if (!target) {
        let obj = {
          title: payload.title,
          price: payload.price,
          count: 1,
          id: payload.id,
        };
        state.cartData.push(obj);
      } else {
        //-有 如果有，让数量count +1
        console.log(target);
        target.count++;
      }
      // state.cartData.push(payload)
    },
    //减少cartData中的数量
    DEL_CARTDADA_COUNT(state, payload) {
      console.log(payload);
      let target = state.cartData.find((item) => item.id === payload.id);
      if (target) {
        target.count--;
      }
      //filter过滤
      state.cartData = state.cartData.filter((item) => item.count);
    },
  },
  actions: {
    ADD_CART(context, payload) {
      //这么写的目的是为了能够学到如何在一个模块化的store操作另一个store的mutation或者action
      // console.log('cart action----',payload)
      context.commit("SET_CART", payload);

      //需要提交另一个 store中的mutation,

      //通过传入root:true把这次操作转换为rootStore的操作，等同于
      //this.$store.commit('product/DECREASE_INVENTORY',payload.id)
      context.commit("product/DECREASE_INVENTORY", payload.id, { root: true });
    },
    DEL_CART({ commit }, payload) {
      commit("DEL_CARTDADA_COUNT", payload);
      commit("product/ADD_PRODUCT_DATA_INVENTORY", payload, { root: true });
    },
  },
  getters: {
    //总价计算
    total(state) {
      // reduce 数组的方法 累加 total 累加的值，item每个元素
      return state.cartData
        .reduce((total, item) => {
          return (total += item.price * item.count);
        }, 0)
        .toFixed(2); //保留两位小数点
    },
  },
};
